package com.aaa.cs.service.impl;

import com.aaa.common.constants.ExceptionConstant;
import com.aaa.common.constants.ReturnStatus;
import com.aaa.common.util.CustomException;
import com.aaa.common.util.Result;
import com.aaa.cs.dao.UserDao;
import com.aaa.cs.entity.Role;
import com.aaa.cs.entity.User;
import com.aaa.cs.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 用户信息表(User)表服务实现类
 *
 * @author makejava
 * @since 2020-12-01 14:40:21
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Integer userId) {
        return this.userDao.queryById(userId);
    }

    @Override
    public List<User> list(User user) {
        return userDao.queryAll(user);
    }


    /**
     * 通过实体作为筛选条件查询
     *
     * @param pageNo
     * @param pageSize
     * @param user     实例对象
     * @return 对象列表
     */
    @Override
    public Result queryAll(int pageNo, int pageSize, User user) {
        if(pageNo==0||pageSize==0){
            throw new CustomException(ExceptionConstant.INVALID_ARGUMENT.getErrorCode(),
                    ExceptionConstant.INVALID_ARGUMENT.getErrorMessage());
        }
        //分页
        PageHelper.startPage(pageNo,pageSize);
        PageInfo<User> pageInfo = new PageInfo<User>(userDao.queryAll(user));
        return new Result(ReturnStatus.SUCCESS.getReturnCode(),
                ReturnStatus.SUCCESS.getReturnMsg(), pageInfo);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<User> queryAllByLimit(int offset, int limit) {
        return this.userDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public Result insert(User user) {
        User user1 = new User();
        user1.setUserName(user.getUserName());
        List<User> users = userDao.queryAll(user1);
        if (users == null || users.size() == 0) {
            String passWord = user.getPassword();
            String passWordSalt = UUID.randomUUID().toString().substring(0, 15);
            Sha512Hash sha512Hash = new Sha512Hash(passWord, passWordSalt, 1024);
            user.setPassword(sha512Hash.toString());
            user.setSalt(passWordSalt);
            return new Result(ReturnStatus.SUCCESS.getReturnCode(), ReturnStatus.SUCCESS.getReturnMsg(),
                    this.userDao.insert(user));
        } else {
            return new Result(ReturnStatus.FAIL.getReturnCode() , ReturnStatus.FAIL.getReturnMsg() ,
                    "该用户名已存在");
        }
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
        if(!StringUtils.isEmpty(user.getPassword())){
            String passWord = user.getPassword();
            String passWordSalt = UUID.randomUUID().toString().substring(0, 15);
            Sha512Hash sha512Hash = new Sha512Hash(passWord, passWordSalt, 1024);
            user.setPassword(sha512Hash.toString());
            user.setSalt(passWordSalt);
        }
        this.userDao.update(user);
        return this.queryById(user.getUserId());
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer userId) {
        return this.userDao.deleteById(userId) > 0;
    }

    /**
     * 查询用户id对应的角色id集合
     * @param userId
     * @return
     */
    @Override
    public List<Integer> listRoleIdsByUserId(int userId) {
        return userDao.listRoleIdsByUserId(userId);
    }

    @Override
    public int delteRoleIdsByUserId(int userId) {
        return userDao.delteRoleIdsByUserId(userId);
    }

    @Override
    public int addUserAndRole(int userId, String roleIds) {
        try {
            //调用上面方法，删除该用户关联的所有角色
            this.delteRoleIdsByUserId(userId);
            StringBuffer stringBuffer =new StringBuffer();
            //分割字符串，循环拼接values后面  (1,1),(1,2),(1,10)...
            String[] ridArray = roleIds.split(",");
            for (String rid : ridArray) {
                stringBuffer.append("("+userId+","+rid+"),");
            }
            String values=stringBuffer.substring(0,stringBuffer.length()-1);
            userDao.addUserAndRole(values);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public User queryByUserName(String userName) {
        User paramUser  = new User();
        paramUser.setUserName(userName);
        paramUser.setStatus("0");
        List<User> users = userDao.queryAll(paramUser);
        //判断是否为空
        if(!CollectionUtils.isEmpty(users)){
            return  users.get(0);
        }
        return null;
    }
}